<template>
  <a-modal v-model:visible="visible" ok-text="确认" cancel-text="取消" :footer="null" :closable="false"
    :bodyStyle="{ padding: 0 }">
    <a-dropdown>
      <a-input v-model:value="searchValue" size="large" placeholder="菜单搜索：支持菜单名称、路径" @change="onChange" />
      <template #overlay>
        <a-menu>
          <a-menu-item v-if="searchMenuPaths.length === 0">
            <a-empty />
          </a-menu-item>
          <a-menu-item v-else v-for="(item, index) in searchMenuPaths" :key="index" @click="onChangeRoute(item)">
            {{ item.map(item => item.title).join(' > ') }}
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </a-modal>
</template>
<script lang='ts' setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import menuService from "@/service/menuService";
import * as utils from '@/util/util';
import { IMenu } from "@/type/Menu";

let emit = defineEmits(['update:visible'])
let props = defineProps({
  visible: Boolean,
})
let searchValue = ref('');
let menuList: IMenu[] = reactive([]);
let searchMenuPaths: IMenu[][] = reactive([]);
const $router = useRouter();

const onChange = (e: InputEvent) => {
  if (!searchValue.value) {
    searchMenuPaths.length = 0;
    return;
  }
  const res: IMenu[] = utils.getLeaf(menuList, searchValue.value);

  searchMenuPaths.length = 0;
  for (let index in res) {
    const path = utils.getPath(menuList, res[index]);
    searchMenuPaths.push(path);
  }
}
const getMenuList = () => {
  menuService.getMenu().then(res => {
    menuList.length = 0;
    menuList.push(...res.menuList);
  })
}


const onChangeRoute = (param: IMenu[]) => {
  emit('update:visible');
  searchValue.value = '';
  searchMenuPaths.length = 0;
  $router.push(param[param.length - 1].url);
}
onMounted(() => {
  getMenuList();
})
</script>
<style lang="less" scoped>

</style>